'''
康爱卫士老年恶性肿瘤疾病保险
'''
import sys
import warnings

warnings.filterwarnings('ignore')
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import urlencode
from common.helper import Helper
from pprint import pprint


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "康爱卫士老年恶性肿瘤疾病保险"

    # 生成产品信息
    def genProductInfo(self):

        # 年缴计划

        plan_year = {

            "planA": {
                # 年龄段 45 - 59
                "year": [str(i) for i in range(45, 60)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": ["20000", "50000", "80000", "100000"],
                # 保障期限
                "expire": ["10年", "20年"],
                # 缴费方式 1 年缴 4 月缴 5 趸交
                "payType": ["年缴"],
                # 缴费间隔
                "interval": ["3", "5", "10"]
            },
            "planB": {
                # 年龄段 60 - 71
                "year": [str(i) for i in range(60, 71)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": ["20000", "50000", "80000", "100000"],
                # 保障期限
                "expire": ["10年"],
                # 缴费方式 1 年缴 4 月缴 5 趸交
                "payType": ["年缴"],
                # 缴费间隔
                "interval": ["3", "5", "10"]
            },
            "planC": {
                # 年龄段 60 - 71
                "year": [str(i) for i in range(71, 76)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": ["20000", "50000", "80000", "100000"],
                # 保障期限
                "expire": ["10年"],
                # 缴费方式 1 年缴 4 月缴 5 趸交
                "payType": ["年缴"],
                # 缴费间隔
                "interval": ["3", "5"]
            },
        }

        for x in plan_year:

            for v in product(plan_year[x]["year"], plan_year[x]["gender"], plan_year[x]["money"],
                             plan_year[x]["expire"], plan_year[x]["payType"], plan_year[x]["interval"]):
                # 写入数据库
                # 写入数据库
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))

        # 月缴计划
        plan_month = {

            "planA": {
                # 年龄段 45 - 59
                "year": [str(i) for i in range(45, 60)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": ["20000", "50000", "80000", "100000"],
                # 保障期限
                "expire": ["10年", "20年"],
                # 缴费方式 1 年缴 4 月缴 5 趸交
                "payType": ["月缴"],
                # 缴费间隔 03 36个月 05 60个月 10 120个月 20 240个月
                "interval": ["03", "05", "10", "20"]
            },
            "planB": {
                # 年龄段 60 - 71
                "year": [str(i) for i in range(60, 71)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": ["20000", "50000", "80000", "100000"],
                # 保障期限
                "expire": ["10年"],
                # 缴费方式 1 年缴 4 月缴 5 趸交
                "payType": ["月缴"],
                # 缴费间隔
                "interval": ["03", "05", "10"]
            },
            "planC": {
                # 年龄段 60 - 71
                "year": [str(i) for i in range(71, 76)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": ["20000", "50000", "80000", "100000"],
                # 保障期限
                "expire": ["10年"],
                # 缴费方式 1 年缴 4 月缴 5 趸交
                "payType": ["月缴"],
                # 缴费间隔
                "interval": ["03", "05"]
            },

        }
        for x in plan_month:

            for v in product(plan_month[x]["year"], plan_month[x]["gender"], plan_month[x]["money"],
                             plan_month[x]["expire"], plan_month[x]["payType"], plan_month[x]["interval"]):
                # 写入数据库
                # 写入数据库
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))

        # 趸交计划
        plan_all = {
            "planA": {
                # 年龄段 45 - 59
                "year": [str(i) for i in range(45, 60)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": ["20000", "50000", "80000", "100000"],
                # 保障期限
                "expire": ["10年", "20年"],
                # 缴费方式 1 年缴 4 月缴 5 趸交
                "payType": ["趸交"],
                # 缴费间隔 03 36个月 05 60个月 10 120个月 20 240个月
                "interval": ["03", "05", "10", "20"]
            },
            "planB": {
                # 年龄段 60 - 71
                "year": [str(i) for i in range(60, 76)],
                # 性别
                "gender": ["M", "F"],
                # 保障金额
                "money": ["20000", "50000", "80000", "100000"],
                # 保障期限
                "expire": ["10年"],
                # 缴费方式 1 年缴 4 月缴 5 趸交
                "payType": ["趸交"],
                # 缴费间隔
                "interval": ["03", "05", "10"]
            },
        }

        for x in plan_all:

            for v in product(plan_all[x]["year"], plan_all[x]["gender"], plan_all[x]["money"],
                             plan_all[x]["expire"], plan_all[x]["payType"], plan_all[x]["interval"]):
                # 写入数据库
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], v[5]))

    # 执行爬虫
    def requestJson(self, dt=None):

        data = self.filterResult(dt)

        pprint(dt)

        print( data )

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=urlencode(data))

        if r.status_code == 200 and "计算保费成功" in r.text :
            price = Helper.decimalParse( r.json()["totalPremium"])
            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

            print("产品价格更新失败:", dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)


    def filterResult(self, dt=None):

        if dt["payType"] == "年缴":

            print("~~~~~~~~~~年缴~~~~~~~~~~")

            if dt["expire"] == "10年":

                data = {

                    "pageName": "productAdd",
                    "goods_id": "61860",
                    "merchant_id": "B2C",
                    "toubaoli_money": "",
                    "productCode": "50000730",
                    "productId": "397ed51c-038b - 4f5a - 9444 - bbe9b4473bca",
                    "riskCode": "0110000195",
                    "productName": "康爱卫士老年恶性肿瘤疾病保险",
                    "insuredPrice": "24484",
                    "insured.birthday": "",
                    "templateType": "1",
                    "employee_id": "",
                    "channel": "GWSC - MENU - M11",
                    "empNo": "",
                    "newsCode": "",
                    "twoMonthInsuredPrice": "48968.00",
                    "loginUserId": "",
                    "insured.age": dt["year"],
                    "insured.sex": "1" if dt["gender"] == "M" else "2",
                    "policy.amount": "10" if dt["money"] == "100000" else "0" + dt["money"][::5],
                    "policy.dateRemark": dt["expire"].replace("年", ""),
                    "policy.chargeType": "1",
                    "policy.chargeYear": "10" if dt["interval"] == "10" else "0" + dt["interval"],
                    "policy.showMessage": "true",
                    "person.mobilenum": "承保短信将发送至您的手机"

                }
                return data

            else:

                data = {

                    "pageName": "productAdd",
                    "goods_id": "61860",
                    "merchant_id": "B2C",
                    "toubaoli_money": "",
                    "productCode": "50000731",
                    "productId": "397ed51c-038b - 4f5a - 9444 - bbe9b4473bca",
                    "riskCode": "0110000195",
                    "productName": "康爱卫士老年恶性肿瘤疾病保险",
                    "insuredPrice": "24484",
                    "insured.birthday": "",
                    "templateType": "1",
                    "employee_id": "",
                    "channel": "GWSC - MENU - M11",
                    "empNo": "",
                    "newsCode": "",
                    "twoMonthInsuredPrice": "48968.00",
                    "loginUserId": "",
                    "insured.age": dt["year"],
                    "insured.sex": "1" if dt["gender"] == "M" else "2",
                    "policy.amount": "10" if dt["money"] == "100000" else "0" + dt["money"][::5],
                    "policy.dateRemark": dt["expire"].replace("年", ""),
                    "policy.chargeType": "1",
                    "policy.chargeYear": "10" if dt["interval"] == "10" else "0" + dt["interval"],
                    "policy.showMessage": "true",
                    "person.mobilenum": "承保短信将发送至您的手机"

                }
                return data



        elif dt["payType"] == "月缴":

            print("~~~~~~~~~~月缴~~~~~~~~~~")

            if dt["expire"] == "10年":

                data = {

                    "pageName": "productAdd",
                    "goods_id": "61860",
                    "merchant_id": "B2C",
                    "toubaoli_money": "",
                    "productCode": "50000730",
                    "productId": "397ed51c-038b - 4f5a - 9444 - bbe9b4473bca",
                    "riskCode": "0110000195",
                    "productName": "康爱卫士老年恶性肿瘤疾病保险",
                    "insuredPrice": "24484",
                    "insured.birthday": "",
                    "templateType": "1",
                    "employee_id": "",
                    "channel": "GWSC - MENU - M11",
                    "empNo": "",
                    "newsCode": "",
                    "twoMonthInsuredPrice": "48968.00",
                    "loginUserId": "",
                    "insured.age": dt["year"],
                    "insured.sex": "1" if dt["gender"] == "M" else "2",
                    "policy.amount": "10" if dt["money"] == "100000" else "0" + dt["money"][::5],
                    "policy.dateRemark": dt["expire"].replace("年", ""),
                    "policy.chargeType": "1",
                    "policy.chargeYear": dt["interval"] if int(dt["interval"]) >= 10 else "0" + dt["interval"],
                    "policy.showMessage": "true",
                    "person.mobilenum": "承保短信将发送至您的手机"

                }
                return data

            else:

                data = {

                    "pageName": "productAdd",
                    "goods_id": "61860",
                    "merchant_id": "B2C",
                    "toubaoli_money": "",
                    "productCode": "50000731",
                    "productId": "397ed51c-038b - 4f5a - 9444 - bbe9b4473bca",
                    "riskCode": "0110000195",
                    "productName": "康爱卫士老年恶性肿瘤疾病保险",
                    "insuredPrice": "24484",
                    "insured.birthday": "",
                    "templateType": "1",
                    "employee_id": "",
                    "channel": "GWSC - MENU - M11",
                    "empNo": "",
                    "newsCode": "",
                    "twoMonthInsuredPrice": "48968.00",
                    "loginUserId": "",
                    "insured.age": dt["year"],
                    "insured.sex": "1" if dt["gender"] == "M" else "2",
                    "policy.amount": "10" if dt["money"] == "100000" else "0" + dt["money"][::5],
                    "policy.dateRemark": dt["expire"].replace("年", ""),
                    "policy.chargeType": "1",
                    "policy.chargeYear": dt["interval"] if int(dt["interval"]) >= 10 else "0" + dt["interval"],
                    "policy.showMessage": "true",
                    "person.mobilenum": "承保短信将发送至您的手机"

                }
                return data


        else:

            print("~~~~~~~~~~趸交~~~~~~~~~~")

            if dt["expire"] == "10年":

                data = {

                    "pageName": "productAdd",
                    "goods_id": "61860",
                    "merchant_id": "B2C",
                    "toubaoli_money": "",
                    "productCode": "50000730",
                    "productId": "397ed51c-038b - 4f5a - 9444 - bbe9b4473bca",
                    "riskCode": "0110000195",
                    "productName": "康爱卫士老年恶性肿瘤疾病保险",
                    "insuredPrice": "24484",
                    "insured.birthday": "",
                    "templateType": "1",
                    "employee_id": "",
                    "channel": "GWSC - MENU - M11",
                    "empNo": "",
                    "newsCode": "",
                    "twoMonthInsuredPrice": "48968.00",
                    "loginUserId": "",
                    "insured.age": dt["year"],
                    "insured.sex": "1" if dt["gender"] == "M" else "2",
                    "policy.amount": "10" if dt["money"] == "100000" else "0" + dt["money"][::5],
                    "policy.dateRemark": dt["expire"].replace("年", ""),
                    "policy.chargeType": "1",
                    "policy.chargeYear": "10" if dt["interval"] == "10" else "0" + dt["interval"],
                    "policy.showMessage": "true",
                    "person.mobilenum": "承保短信将发送至您的手机"

                }
                return data

            else:

                data = {

                    "pageName": "productAdd",
                    "goods_id": "61860",
                    "merchant_id": "B2C",
                    "toubaoli_money": "",
                    "productCode": "50000731",
                    "productId": "397ed51c-038b - 4f5a - 9444 - bbe9b4473bca",
                    "riskCode": "0110000195",
                    "productName": "康爱卫士老年恶性肿瘤疾病保险",
                    "insuredPrice": "24484",
                    "insured.birthday": "",
                    "templateType": "1",
                    "employee_id": "",
                    "channel": "GWSC - MENU - M11",
                    "empNo": "",
                    "newsCode": "",
                    "twoMonthInsuredPrice": "48968.00",
                    "loginUserId": "",
                    "insured.age": dt["year"],
                    "insured.sex": "1" if dt["gender"] == "M" else "2",
                    "policy.amount": "10" if dt["money"] == "100000" else "0" + dt["money"][::5],
                    "policy.dateRemark": dt["expire"].replace("年", ""),
                    "policy.chargeType": "1",
                    "policy.chargeYear": "10" if dt["interval"] == "10" else dt["interval"],
                    "policy.showMessage": "true",
                    "person.mobilenum": "承保短信将发送至您的手机"

                }
                return data

